package model;



import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

// 数据库相关操作
// 单例模式
// 懒汉模式实现单例模式;
public class DBUtil {
   private static DataSource dataSource = null;
   // SSL 那块我没看 但是这个老报错 所以 我将SSL=true 改成了 SSL=false;
   private static final String URL = "jdbc:mysql://127.0.0.1:3306/blogs?characterEncoding=utf8&useSSL=false";
   private static final String USERNAME = "root";
   private static final String PASSWORD = "root";

   // 获取数据库连接池 懒汉模式实现;
   public static DataSource getDataSource(){
       if (dataSource == null) {
           synchronized (DBUtil.class) {
               if(dataSource == null){
                   dataSource = new MysqlDataSource();
                   ((MysqlDataSource)dataSource).setURL(URL);
                   ((MysqlDataSource)dataSource).setUser(USERNAME);
                   ((MysqlDataSource)dataSource).setPassword(PASSWORD);
               }
           }
       }
       return dataSource;
   }

   // 获取数据库连接对象;
   public static Connection getConnection() {
       try {
           return getDataSource().getConnection();
       } catch (SQLException throwable) {
           throwable.printStackTrace();
       }
       return null;
   }

   // 关闭数据库连接
    public static void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet){

           try {
               if(resultSet != null) resultSet.close();
               if(preparedStatement != null) preparedStatement.close();
               if(connection != null) connection.close();
           } catch (SQLException throwable) {
               throwable.printStackTrace();
           }

    }
}
